package com.zxy.controller;

import com.zxy.annotation.RequestMapping;
import com.zxy.annotation.RequestMappingHandler;
import org.apache.commons.io.IOUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @author zxy
 * @date 2019-04-28 16:38
 */
@WebServlet("/editormd/*")
public class EditormdController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String requestURI = request.getRequestURI();
        String action = requestURI.substring(request.getServletContext().getContextPath().length() + 1);
        action = action.substring(action.indexOf("/"));
        RequestMappingHandler.handle(this.getClass(), this, action, request, response);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        doPost(req, resp);
    }

    @RequestMapping("/save")
    public void staticMap(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, token");

        String mdContent = "";
        String fileName;
        if (request.getParameter("mdContent") != null) {
            mdContent = request.getParameter("mdContent");
        }
        if (request.getParameter("fileName") != null && !"".equals(request.getParameter("fileName"))) {
            fileName = request.getParameter("fileName") + ".md";
        } else {
            fileName = String.format("%s.md", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        }
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
        OutputStream outputStream = response.getOutputStream();
        InputStream is = new ByteArrayInputStream(mdContent.getBytes());
        IOUtils.copy(Objects.requireNonNull(is), outputStream);
    }

    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) {
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.addHeader("Access-Control-Max-Age", "3600");
        resp.addHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
        resp.addHeader("Access-Control-Allow-Headers", "User-Agent,Origin,Cache-Control,Content-type,x-zd,Date,Server,withCredentials");
    }
}
